<template>
	<view @touchmove.stop.prevent="() => {}" @tap.stop.prevent="() => {}">
		<block>
			<u-popup ref="uPopup" mode="top" @open="popupOpen" @close="popupClose">
				<!-- selectIndex的值绑定当前选中项的值 -->
				<scroll-view :scroll-top="scrollTop" scroll-y="true" :style="{height: this.$u.addUnit(height)}">
					<view class="cell-list">
						<view class="cell-item" @click="cellClick(index)" v-for="(item, index) in options" :key="index"
							:style="{
							color: selectIndex == index ? activeColor : inactiveColor,
						}">

							{{item[title]}}

							<view class="select-icon">
								<u-icon v-if="selectIndex == index" name="checkbox-mark" :color="activeColor"
									size="32" />
							</view>

						</view>

					</view>
				</scroll-view>
			</u-popup>
		</block>
	</view>
</template>

<script>
	export default {
		name: 'custom-dropdown-list',
		props: {
			// 使用v-model同步开启与关闭状态
			value: {
				type: Boolean,
				required: true,
				default: false
			},
			// 当前选中项的索引值
			selectIndex: {
				type: Number,
				default: 0
			},
			// 菜单项标题对应数组对象的Key
			title: {
				type: String,
				default: ''
			},
			// 选项数据，如果传入了默认slot，此参数无效
			options: {
				type: Array,
				default () {
					return []
				}
			},
			// 下拉弹窗的高度
			height: {
				type: [Number, String],
				default: 'auto'
			},
		},
		data() {
			return {
				// 处理回到顶部的问题
				scrollTop: 0,
				activeColor: '#fff', // 激活时左边文字和右边对勾图标的颜色
				inactiveColor: '#ddd', // 未激活时左边文字和右边对勾图标的颜色
			}
		},
		watch: {
			value(newValue) {
				if (newValue) {
					this.$refs.uPopup.open();
				}
			}
		},
		methods: {
			// 窗口打开时同步索引位置
			popupOpen() {
				//查询cell-item的大小并这是偏移量
				let view = uni.createSelectorQuery().in(this).select(".cell-item");			
				view.fields({
				  size: true,
				}, data => {
				  // 同步选中状态
				  this.$nextTick(() => {
				  	this.scrollTop = (this.selectIndex - 3) *  data.height;
				  });
				}).exec();
				
			},
			// 窗口关闭时同步状态
			popupClose() {
				this.$emit('input', false);
			},
			// cell被点击
			cellClick(value) {
				// 发出事件，抛出当前勾选项的value
				this.$emit('change', value);
				// 关闭Popup
				this.$refs.uPopup.close();
			}
		},
	}
</script>

<style scoped lang="scss">
	// @import "uview-ui/libs/css/style.components.scss";
	.cell-list {
		background-color: #239ff6;
		padding: 0 25rpx;
	}

	.cell-item {
		display: flex;
		height: 80rpx;
		line-height: 80rpx;

		.select-icon {
			flex: 1;
			text-align: right;
		}
	}
</style>
